﻿#include "imageview.h"
#include "dropeater.h"
#include "pluginframeworkhelper.h"

#include <imageviewwidget.h>
#include <QLayout>
#include <QMainWindow>
#include <QMessageBox>
#include <eventutil.h>

ImageView::ImageView(QObject *parent)
    : QObject{parent}
{

}

ImageView &ImageView::instance()
{
    static ImageView _plugin;
    return _plugin;
}

QString ImageView::PluginName()
{
    return "图片预览";
}

QString ImageView::PluginVersion()
{
    return "v0.1";
}

QString ImageView::PluginAuthor()
{
    return "zinface";
}

QString ImageView::PluginComment()
{
    return "支持图片直接拖入到ndd工具栏中自动展开显示，在预览界面中支持拖入面板。";
}

IPluginFramework::MenuType ImageView::PluginMenuType()
{
    return MenuType::None;
}

void ImageView::registerNotepad(QWidget *notepad)
{
    s_notepad = notepad;

    view = new ImageViewWidget(s_notepad);
    QWidget *edit = (dynamic_cast<QMainWindow*>(s_notepad))->findChild<QWidget*>("editTabWidget");
    if (edit == nullptr) {
        return;
    }
    ((QLayout*)(dynamic_cast<QMainWindow*>(s_notepad))->centralWidget()->layout())->addWidget(view);
    view->hide();
    connect(view, &ImageViewWidget::onHiddend, edit, &QWidget::show);

    new DropEater([this, edit](QDropEvent *event){
        auto filepath = EventUtil::getDropOneFileName(event);
        if (filepath.endsWith("jpg") ||
            filepath.endsWith("jpeg") ||
            filepath.endsWith("png") ||
            filepath.endsWith("bmp") ||
            filepath.endsWith("gif")) {
            edit->hide();
            view->show();
            view->setFilePath(EventUtil::getDropOneFileName(event));
            return true;
        }
        return false;
    }, s_notepad);
}

void ImageView::registerStrFileName(QString str_file_name)
{
    s_str_file_name = str_file_name;
}

void ImageView::PluginTrigger()
{
    // QMessageBox::information(nullptr, "tip", "This is default tip message.");
    QWidget *edit = (dynamic_cast<QMainWindow*>(s_notepad))->findChild<QWidget*>("editTabWidget");
    if (edit == nullptr) {
        return;
    }
    edit->hide();
    view->show();
}

void ImageView::registerPluginActions(QMenu *rootMenu)
{
    //Actions: Will never enter here.
}

void ImageView::registerCurrentEditCallback(std::function<QsciScintilla *(QWidget *)> get_cur_edit_callback)
{
    s_get_cur_edit_callback = get_cur_edit_callback;
}

void ImageView::registerPluginCallBack(std::function<bool (QWidget *, int, void *)> plugin_callback)
{
    s_plugin_callback = plugin_callback;
}

// Plug-in implementation wrapper
NDD_DECLARE_PLUGIN(ImageView::instance())
